﻿using System;

namespace ListForEach
{
    
    class Program
    {
        public class Node<T>
        {
            public Node<T> Next { get; set; }
            public T Data { get; set; }
            public Node(T t)
            {
                Next = null;
                Data = t;
            }
        }

        public class GenericList<T>
        {
            private Node<T> head;
            private Node<T> tail;

            public GenericList()
            {
                head = tail = null;
            }

            public Node<T> Head
            {
                get => head;
            }

            public void Add(T t)
            {
                Node<T> n = new Node<T>(t);
                if (tail == null)
                {
                    head = tail = n;
                }
                else
                {
                    tail.Next = n;
                    tail = n;
                }
            }

            public void ForEvery(Action<T> action)
            {
                Node<T> node = this.Head;
                while(node != null)
                {
                    action(node.Data);
                    node = node.Next;
                }
            }
        }

        static void Main(string[] args)
        {
            GenericList<int> intList = new GenericList<int>();
            for(int i = 0; i < 10; i++)
            {
                intList.Add(i);
            }
            for(Node<int> node = intList.Head; node != null; node = node.Next)
            {
                Console.WriteLine(node.Data);
            }

            GenericList<string> stringList = new GenericList<string>();
            for (int i = 0; i < 10; i++)
            {
                stringList.Add("str"+i);
            }
            for (Node<string> node = stringList.Head; node != null; node = node.Next)
            {
                Console.WriteLine(node.Data);
            }

            Console.WriteLine("实现List的ForEach功能：");
            //打印全部元素
            intList.ForEvery(m => Console.WriteLine(m));

            //求和
            int sum = 0;
            intList.ForEvery(m => sum += m);
            Console.WriteLine("sum = " + sum);

            //求最大值和最小值
            int max = -1, min = 100;
            intList.ForEvery(m => 
            { if (m > max) 
                    max = m; });
            Console.WriteLine("max = " + max);

            intList.ForEvery(m =>
            {
                if (m < min)
                    min = m;
            });
            Console.WriteLine("min = " + min);

        }
    }
}
